package com.cloudcc.mobile.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.BusinesscardAdapter;
import com.cloudcc.mobile.dao.CallLogDao;
import com.cloudcc.mobile.dao.impl.CallLogDaoImpl;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.entity.MoreJurisdictionEntity;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.gson.Gson;
import com.intsig.openapilib.OpenApi;
import com.intsig.openapilib.OpenApiParams;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.model.loginyz;
import com.mypage.model.secondlogin;
import com.mypage.view.activity.SecondLogin;
import com.zbar.lib.CaptureActivity;

import java.util.List;

/**
 * 名片扫描
 *
 * @author Administrator
 */
public class BusinesscardScanningActivity extends BaseActivity implements IEventLife, View.OnClickListener {
    private static final float MAX_Z_DP = 10;
    private static final float MOMENTUM_SCALE = 10;
    private static final int MAX_ANGLE = 10;
    private String replay = "";
    private LinearLayout lead, account;
    private String imagePath;
    private String codes;
    private CallLogDao callLogDao;
    private CallLogLoadingDialog loadingDialog;
    private List<MoreJurisdictionEntity> lists;
    private boolean kehuqx, contastqx;
    OpenApi openApi = OpenApi.instance("7y43139YE8TBXB98r17aRLyb");
    OpenApiParams apiParams = new OpenApiParams() {
        {
            this.setRecognizeLanguage("");
            this.setReturnCropImage(true);
            this.setSaveCard(true);
        }
    };

    private RelativeLayout qianke, kehu, saoma;
    private View qiankeLine , kehuLine;

    public void init(Bundle savedInstanceState) {
        EventEngine.register(this);
        setupView();
    }

    ;

    @Override
    public int getLayoutId() {
        return R.layout.businesscardscanning;
    }

    private RecyclerView mRe;
    private BusinesscardAdapter adapter;

    @SuppressLint("NewApi")
    private void setupView() {

//		TextView tvheader = (TextView) findViewById(R.id.header_title);
        ImageView imageView = (ImageView) findViewById(R.id.saoyiso_backuser);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        qianke = (RelativeLayout) findViewById(R.id.cord_qianke);
        kehu = (RelativeLayout) findViewById(R.id.cord_kehu);
        saoma = (RelativeLayout) findViewById(R.id.card_login);
        qiankeLine = findViewById(R.id.cord_qianke_line);
        kehuLine = findViewById(R.id.cord_kehu_line);
        qianke.setOnClickListener(this);
        kehu.setOnClickListener(this);
        saoma.setOnClickListener(this);

        loadingDialog = new CallLogLoadingDialog(this, R.style.DialogLoadingTheme);
        loadingDialog.show();
        loadingDialog.settext(getString(R.string.zhengzaijiazais));
        getJurisdiction();
    }


    // 扫一扫返回
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("saoyisao", "扫一扫返回" + requestCode + "resultCode"
                + (resultCode == Activity.RESULT_OK));
        if (requestCode == 10001 && resultCode == Activity.RESULT_OK) {

            String result1 = data.getStringExtra("result");
            try {


                final Gson gson = new Gson();
                final loginyz ss = gson.fromJson(result1,
                        loginyz.class);

                HttpUtils utils = new HttpUtils();
                RequestParams params = new RequestParams();
//					/distributor.action?serviceName=scaned&uuid=xxxxx
                params.addBodyParameter("serviceName", "scaned");

                params.addBodyParameter("uuid", ss.uuid);
                Log.d("request",
                        "链接" + UrlManager.getInterfaceUrl()
                                + GsonUtil.Object2Json(params));

                String url = "";

                if (UrlManager.getInterfaceYm().contains(ss.hostName)) {
                    url = UrlManager.getInterfaceUrl();
                } else if ("120.27.162.206:9004".equals(ss.hostName)) {
                    url = "http://120.27.162.206:9004/distributor.action";
//					else if("login.cloudcc.com".equals(ss.hostName)){
//						url = "http://login.cloudcc.com/distributor.action";  http://120.27.162.206:9004/
                } else {
                    showToast(getResources().getString(R.string.saonoerweima));
                    return;
                }
                utils.send(HttpMethod.POST, url, params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onFailure(HttpException arg0, String arg1) {
                                Log.d("-------------------------", "Failure。。。"
                                        + arg1.toString());
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> arg0) {
                                Log.d("-------------------------", "success。。。"
                                        + arg0.result);

                                secondlogin secondlogin = gson.fromJson(arg0.result, secondlogin.class);
                                if ("false".equals(secondlogin.result)) {
                                    showToast(secondlogin.returnInfo);
                                } else {
                                    Intent intent = new Intent(mContext, SecondLogin.class);
                                    intent.putExtra("hostname", ss.hostName);
                                    intent.putExtra("uuid", ss.uuid);
                                    intent.putExtra("time", secondlogin.data.validTime);
                                    startActivityForResult(intent, 10002);
//                                    finish();
                                }
                            }


                        });
            } catch (Exception e) {
                // TODO: handle exception
                showToast(getResources().getString(R.string.saonoerweima));
            }

        }
        if (requestCode == 10008 && resultCode == Activity.RESULT_OK) {
            imagePath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
            Intent intent = new Intent(this, NameCordKingActivity.class);
            intent.putExtra(SelectPicActivity.KEY_PHOTO_PATH, imagePath);
            intent.putExtra("codes", codes);
            startActivity(intent);
        }
        if (requestCode == 10002 && resultCode == -2) {
            Intent intent = new Intent(BusinesscardScanningActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 10001);
        }
    }


    /**
     * 获取多个对象权限：001,003,004 == 客户 联系人 潜在客户
     */
    private void getJurisdiction() {
        callLogDao = new CallLogDaoImpl();
        BeauEventList.MoreJurisdictionEvent event = new BeauEventList.MoreJurisdictionEvent();
        callLogDao.getMoreJurisdiction("001,003,004", event);
    }

    public void onEventMainThread(BeauEventList.MoreJurisdictionEvent event) {
        if (event.isError()) {
            qianke.setVisibility(View.GONE);
            qiankeLine.setVisibility(View.GONE);
            kehu.setVisibility(View.GONE);
            kehuLine.setVisibility(View.GONE);
            return;
        }
        loadingDialog.dismiss();
        lists = event.getData();
        for (MoreJurisdictionEntity moreJurisdictionEntity : lists) {
            if (moreJurisdictionEntity.objPrefix.equals("001")) {//客户
                if (moreJurisdictionEntity.objstatus.equals("true")) {
                    if(moreJurisdictionEntity.permMap.add){
                        kehuqx = true;
                    }else{
                        kehuqx = false;
                    }
                } else {
                    kehuqx = false;
                }

            }
            if (moreJurisdictionEntity.objPrefix.equals("003")) {//联系人
                if (moreJurisdictionEntity.objstatus.equals("true")) {
                    if(moreJurisdictionEntity.permMap.add){
                        contastqx = true;
                    }else{
                        contastqx = false;
                    }
                } else {
                    contastqx = false;
                }

            }
            if (moreJurisdictionEntity.objPrefix.equals("004")) {//潜在客户
                if (moreJurisdictionEntity.objstatus.equals("true")) {
                    if(moreJurisdictionEntity.permMap.add){
                    }else{
                        qianke.setVisibility(View.GONE);
                        qiankeLine.setVisibility(View.GONE);
                    }
                } else {
                    qianke.setVisibility(View.GONE);
                    qiankeLine.setVisibility(View.GONE);
                }
            }
        }

        if(!kehuqx  && !contastqx){
            kehu.setVisibility(View.GONE);
            kehuLine.setVisibility(View.GONE);
        }

    }

    public void clickBack(View v) {
        this.finish();
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    protected void onDestroy() {
        EventEngine.uregister(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (v == qianke) {
            //8.0新版跳转选择图片
            codes = "lead";
            Intent intent = new Intent(this,
                    SelectPictureNamecordActivity.class);
            intent.putExtra("codes", codes);
            startActivityForResult(intent, 10008);

        }
        if (v == kehu) {
            //8.0新版跳转选择图片
            codes = "account";
            Intent intent = new Intent(this,
                    SelectPictureNamecordActivity.class);
            intent.putExtra("kehuqx", kehuqx);
            intent.putExtra("contastqx", contastqx);
            intent.putExtra("codes", codes);
            startActivityForResult(intent, 10008);


        }
        if (v == saoma) {
            Intent intent = new Intent(BusinesscardScanningActivity.this, CaptureActivity.class);
//            intent.putExtra("tag","gongniu");
            startActivityForResult(intent, 10001);
        }
    }
}
